package com.chenhb.watermarkutils;

import com.chenhb.watermarkutils.bo.WatermarkBo;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 * 图片添加图片水印工具
 *
 * @author 陈海波
 * @date 2021-04-21
 */
public class ImageImageWatermarkUtil extends AbstractWatermark {
    /**
     * 给图片添加图片水印
     *
     * @param watermarkBo
     */
    public static ByteArrayOutputStream mark(WatermarkBo watermarkBo) {
        ByteArrayOutputStream os = null;
        try {
            Image srcImg = ImageIO.read(watermarkBo.getResourceFile());

            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
                    BufferedImage.TYPE_INT_RGB);

            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0,
                    0, null);

            if (null != watermarkBo.getDegree()) {
                // 设置水印旋转
                g.rotate(Math.toRadians(watermarkBo.getDegree()), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }

            // 水印图象的路径 水印一般为gif或者png的，这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(filetoByte(watermarkBo.getWatermarkImageFile()));

            // 得到Image对象。
            Image img = imgIcon.getImage();
            // 透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, watermarkBo.getTransparency()));

            // 表示水印图片的位置
            g.drawImage(img, watermarkBo.getOffsetX(), watermarkBo.getOffsetY(),
                    watermarkBo.getWidth(), watermarkBo.getHeight(), null);

            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

            g.dispose();

            os = new ByteArrayOutputStream();
            // 获取文件后缀
            String fileName = watermarkBo.getResourceFile().getName();
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 生成图片
            ImageIO.write(buffImg, prefix, os);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        }
        return os;
    }
}
